<?php
$conf = include('typo3conf/LocalConfiguration.php');
$db = $conf['DB'];

// print_r($db);
$link = mysql_connect($db['host'] . ':' . $db['port'], $db['username'], $db['password']);
$db_sel = mysql_select_db($db['database']) or die('Impossible de se connecter : ' . mysql_error());


$req = "SELECT *,sys_file_metadata.uid AS uid_metadata FROM sys_file_metadata JOIN sys_file ON sys_file_metadata.file = sys_file.uid WHERE sys_file_metadata.content_creation_date = 0 and sys_file.storage = 2";
$res = mysql_query($req);


while($line = mysql_fetch_array($res)) {
	// print_r($line);
	unset($data);
	$filename = 'fileadmin/lifein/photos' . $line['identifier'];
	echo $filename . "<br>";
	$data = @exif_read_data($filename, 0, TRUE);
	unset($data['EXIF']['MakerNote']);

	if (is_array($data['EXIF'])) {
		$exif = $data['EXIF'];
		if (is_array($data['IFD0'])) {
			$exif = array_merge($data['IFD0'], $exif);
		}
		if (is_array($data['GPS'])) {
			$exif['GPS'] = ($data['GPS']);
			// $exif['GPS'] = 1;
		}

	$meta = processExifData($metadata, $exif);
	}

	// print_r($meta);
	if(is_array($meta)) {
		$req_u = "UPDATE sys_file_metadata SET ";
		foreach($meta as $field => $value) {
			$value = trim($value);
			$req_u .= $field . " = '" . $value . "', ";
		}
		$req_u .= 'pid = ' . $line['pid'];
		$req_u .= " WHERE uid = '" . $line['uid_metadata'] . "'";
		// echo $req_u . "<br>";
		$res_u = mysql_query($req_u) or die('Erreur a l\'update : ' . mysql_error() . ', Requete : ' . $req_u);
	}
	
}


/**
 * Parse metadata from EXIF incl. IFD0 block
 *
 * @param $metadata
 * @param $exif
 *
 * @return void
 */
function processExifData(&$metadata, $exif) {
	foreach ($exif as $exifAttribute => $value) {

		switch ($exifAttribute) {
			case 'Headline':
			case 'Title':
			case 'XPTitle':
				$metadata['title'] = $value;
				break;

			case 'Subject':
			case 'ImageDescription':
			case 'Description':
				$metadata['description'] = $value;
				break;

			case 'CaptionAbstract':
				$metadata['caption'] = $value;
				break;

			case 'Keywords':
			case 'XPKeywords':
				$metadata['keywords'] = $value;
				break;

			case 'ImageCreated':
			case 'CreateDate':
			case 'DateTimeOriginal':
			case 'DateTimeDigitized':
				$metadata['content_creation_date'] = strtotime($value);
				break;

			case 'ModifyDate':
			case 'DateTime':
				$metadata['content_modification_date'] = strtotime($value);
				break;

			case 'Copyright':
			case 'CopyrightNotice':
			case 'Credit':
			case 'Rights':
				// $metadata['copyright_notice'] = $value;
				break;

			case 'Artist':
			case 'Creator':
				// $metadata['creator'] = $value;
				break;

			case 'ApertureValue':
			case 'MaxApertureValue':
				$parts = explode('/', $value);
				$metadata['aperture_value'] = round(exp(($parts[0] / $parts[1]) * 0.51 * log(2)), 1);
				break;

			case 'ShutterSpeedValue':
				$parts = explode('/', $value);
				$metadata['shutter_speed_value'] = '1/' . (int) pow(2, $parts[0] / $parts[1]);
				break;

			case 'ISOSpeedRatings':
				$metadata['iso_speed_ratings'] = $value;
				break;

			case 'FocalLength':
				$parts = explode('/', $value);
				$metadata['focal_length'] = $parts[0] / $parts[1];
				break;

			case 'CameraModel':
			case 'Model':
				$metadata['camera_model'] = $value;
				break;

			case 'Flash':
				$metadata['flash'] = (int) $value;
				break;

			case 'MeteringMode':
				$metadata['metering_mode'] = (int) $value;
				break;

			case 'ColorSpace':
				$metadata['color_space'] = getColorSpace($value);
				break;

			case 'HorizontalResolution':
			case 'XResolution':
				// TODO: is fractionToInt needed here?
				$metadata['horizontal_resolution'] = fractionToInt($value);
				break;
			case 'VerticalResolution':
			case 'YResolution':
				// TODO: is fractionToInt needed here?
				$metadata['vertical_resolution'] = fractionToInt($value);
				break;

			case 'GPS':
				if (is_array($value)) {
					$metadata['latitude'] = parseGpsCoordinate($value['GPSLatitude'], $value['GPSLatitudeRef']);
					$metadata['longitude'] = parseGpsCoordinate($value['GPSLongitude'], $value['GPSLongitudeRef']);
					
					$xml_content = file_get_contents("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" . $metadata['latitude'] . "," . $metadata['longitude'] . "&sensor=false&region=en");
					$xml = simplexml_load_string($xml_content);
					
					// foreach($xml->result->address_component as $add) {
						// $xml_data[] = $add;
					// }
					
					// \TYPO3\CMS\Core\Utility\GeneralUtility::devLog(
						// 'xmlGeoCode', 
						// 'metadata', 1, 
						// array(
							// "http://maps.googleapis.com/maps/api/geocode/xml?latlng=" . $metadata['latitude'] . "," . $metadata['longitude'] ."&sensor=false&region=gb", 
							// $xml->result,
							// $xml->GeocodeResponse,
							
							// $xml_data)
					// );
					
					// $xml_gps = file_get_contents("http://maps.googleapis.com/maps/api/geocode/xml?latlng=" . $metadata['latitude'] . "," . $metadata['longitude'] ."&sensor=false&region=gb");
				}
				break;

			case 'City':
				$metadata['location_city'] = $value;
				break;

			case 'Country':
				$metadata['location_country'] = $value;
				break;

			case 'CreatorTool':
			case 'Software':
				$metadata['creator_tool'] = $value;
				break;

			default:
		}
	}
	
	return $metadata;
}

	/**
	 * Converting GPS
	 *
	 * @param array $value
	 * @param string $ref
	 *
	 * @return string
	 */
	function parseGpsCoordinate($value, $ref) {
		if (is_array($value)) {
			$neutralValue = fractionToInt($value[0]) + (((fractionToInt($value[1]) * 60) + (fractionToInt($value[2]))) / 3600);
			$value = ($ref === 'N' || $ref === 'E') ? $neutralValue : '-' . $neutralValue;
		}

		return (string) $value;
	}

	/**
	 * Calculates a fraction
	 */
	function fractionToInt($fraction) {
		$fractionParts = explode('/', $fraction);

		return intval($fractionParts[0] / $fractionParts[1]);
	}

	/**
	 * Converts the color space id to the value in Media Management
	 *
	 * @param int $value
	 *
	 * @return string
	 */
	function getColorSpace($value) {
		$colorSpaceToNameMapping = array(
		'0' => 'grey',
		'1' => 'sRGB',
		'2' => 'RGB',
		'3' => 'RGB',
		'4' => 'grey',
		'6' => 'RGB',
	);
	
		if (array_key_exists($value, $colorSpaceToNameMapping)) {
			$value = $colorSpaceToNameMapping[$value];
		}

		return (string) $value;
	}



